package com.sgcc.sx.pmos.e_sx_home.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.GsonUtils;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.sx.pmos.arouter.home.HomeArouterPath;
import com.sgcc.sx.pmos.common.base.BaseActivity;
import com.sgcc.sx.pmos.common.base.BaseRecyclerAdapter;
import com.sgcc.sx.pmos.common.bean.EventCenter;
import com.sgcc.sx.pmos.common.utils.ArguConstant;
import com.sgcc.sx.pmos.common.utils.AssetsUtil;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.sx.pmos.e_sx_home.adapter.AddressAdapter;
import com.sgcc.sx.pmos.e_sx_home.bean.AddressBean;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@Route(path = HomeArouterPath.HOME_SELECTADDRESS)
public class SelectAddressActivity extends BaseActivity {

    private TitleBar mTitleBar;
    private TextView mTvLocation;
    private TextView mTvLocation1;
    private TextView mTvLocation2;
    private TextView mTvLocation3;
    private RecyclerView mRvContent;
    private LocationManager myLocationManager;
    private AddressAdapter mAdapter;
    private List<AddressBean.DataBean.ObjListBean> mList = new ArrayList<>();

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_selectaddress_sx;
    }

    @Override
    protected void initViews() {
        super.initViews();
        findViewByIds();

//        XXPermissionsUtil.location(SelectAddressActivity.this, new XXPermissionsUtil.PermissionCallback() {
//            @Override
//            public void Call() {
//                initLocationData();
//            }
//        });

        String json = AssetsUtil.readStringFromAssets("address.json");
        AddressBean response = GsonUtils.fromJson(json, AddressBean.class);
        mList.addAll(response.getData().getObjList());

        mRvContent.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        mAdapter = new AddressAdapter();
        mAdapter.setListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                if (data instanceof AddressBean.DataBean.ObjListBean.ProvincesBean) {
                    onAddressSelect((AddressBean.DataBean.ObjListBean.ProvincesBean) data);
                }
            }
        });
        mRvContent.setAdapter(mAdapter);
        mAdapter.setMlist(mList);
    }

    private AddressBean.DataBean.ObjListBean.ProvincesBean getDataByName(String name) {
        if (mList.size() == 0) return null;
        for (int i = 0; i < mList.size(); i++) {
            List<AddressBean.DataBean.ObjListBean.ProvincesBean> provinces = mList.get(i).getProvinces();
            for (int j = 0; j < provinces.size(); j++) {
                AddressBean.DataBean.ObjListBean.ProvincesBean bean1 = provinces.get(j);
                if (bean1.getNetProvinceName().contains(name)) {
                    return bean1;
                }
            }
        }
        return getDataByName("首都");
    }

    private void initNear(TextView view, AddressBean.DataBean.ObjListBean.ProvincesBean bean) {
        if (bean == null) {
            view.setVisibility(View.INVISIBLE);
            return;
        }
        view.setVisibility(View.VISIBLE);
        String netProvinceName = bean.getNetProvinceName();
        if (netProvinceName.contains("电力交易中心")) {
            netProvinceName = netProvinceName.replace("电力交易中心", "");
        }
        view.setText(netProvinceName);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onAddressSelect(bean);
            }
        });
    }

    private void showLocationError() {
        mTvLocation1.setText("山西");
        mTvLocation1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initNear(mTvLocation1, getDataByName("山西"));
            }
        });
    }

    private void onAddressSelect(AddressBean.DataBean.ObjListBean.ProvincesBean bean) {
        if (bean != null) {
            EventBus.getDefault().post(new EventCenter<>(ArguConstant.SELECTADDRESS, bean));
            finish();
        }
    }

    private void findViewByIds() {
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTvLocation = (TextView) findViewById(R.id.tv_location);
        mTvLocation1 = (TextView) findViewById(R.id.tv_location1);
        mTvLocation2 = (TextView) findViewById(R.id.tv_location2);
        mTvLocation3 = (TextView) findViewById(R.id.tv_location3);
        mRvContent = (RecyclerView) findViewById(R.id.rv_content);

        mTitleBar.setTitle("场景切换");
        showLocationError();
    }

    private void initLocationData() {
        getAddress(getLocation(), address -> {
            if (address != null && address.size() != 0 && !TextUtils.isEmpty(address.get(0).getAddressLine(0))) {
                String locality = address.get(0).getAddressLine(0);
                if (locality.contains("市")) {
                    locality = locality.substring(0, locality.indexOf("市") + 1);
                }
                mTvLocation.setText(locality);
                if (!"中国".equals(address.get(0).getCountryName())) {
                    mTvLocation.setText("国外");
                    showLocationError();
                    return;
                }
                if (locality.contains("省")) {
                    String netName = locality.substring(0, locality.indexOf("省"));
                    if ("河北".equals(netName)) {
                        if (locality.contains("市")) {
                            String shi = locality.substring(locality.indexOf("省") + 1, locality.indexOf("市"));
                            if ("张家口".equals(shi) || "承德".equals(shi) || "唐山".equals(shi)) {
                                initNear(mTvLocation1, getDataByName("冀北"));
                            } else {
                                initNear(mTvLocation1, getDataByName(netName));
                            }
                        } else {
                            initNear(mTvLocation1, getDataByName(netName));
                        }
                    } else {
                        initNear(mTvLocation1, getDataByName(netName));
                    }
                } else if (locality.contains("自治区")) {
                    if (locality.startsWith("西藏")) {
                        initNear(mTvLocation1, getDataByName("西藏"));
                    }
                    if (locality.startsWith("宁夏")) {
                        initNear(mTvLocation1, getDataByName("宁夏"));
                    }
                    if (locality.startsWith("新疆")) {
                        initNear(mTvLocation1, getDataByName("新疆"));
                    }
                    if (locality.startsWith("内蒙古")) {
                        initNear(mTvLocation1, getDataByName("蒙东"));
                    }
                } else if (locality.contains("市")) {
                    String netName = locality.substring(0, locality.indexOf("市"));
                    if (netName.equals("北京")) {
                        initNear(mTvLocation1, getDataByName("首都"));
                        initNear(mTvLocation2, getDataByName(netName));
                    } else {
                        initNear(mTvLocation1, getDataByName(netName));
                    }
                } else {
                    showLocationError();
                }
            } else {
                mTvLocation.setText("定位失败");
            }
        });
    }

    @SuppressLint("MissingPermission")
    private Location getLocation() {
        //获取位置管理服务

        //查找服务信息
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE); //定位精度: 最高
        criteria.setAltitudeRequired(false); //海拔信息：不需要
        criteria.setBearingRequired(false); //方位信息: 不需要
        criteria.setCostAllowed(true);  //是否允许付费
        criteria.setPowerRequirement(Criteria.POWER_LOW); //耗电量: 低功耗

        Location gpslocation = null;
        Location netLocation = null;

        myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (gpsIsOpen()) {
            myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 5, locationListener);
            String p = myLocationManager.getBestProvider(criteria, true);
            gpslocation = myLocationManager.getLastKnownLocation(p);
        }
        if (netWorkIsOpen()) {
            myLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 5, locationListener);
            netLocation = myLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }

        if (gpslocation == null && netLocation == null) {
            return null;
        }
        if (gpslocation != null && netLocation != null) {
            if (gpslocation.getTime() < netLocation.getTime()) {
                return netLocation;
            } else {
                return gpslocation;
            }
        }
        if (gpslocation == null) {
            return netLocation;
        } else {
            return gpslocation;
        }
    }

    private boolean gpsIsOpen() {
        boolean isOpen = true;
        if (!myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {//没有开启GPS
            isOpen = false;
        }
        return isOpen;
    }

    private boolean netWorkIsOpen() {
        boolean netIsOpen = true;
        if (!myLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {//没有开启网络定位
            netIsOpen = false;
        }
        return netIsOpen;
    }

    private interface LocationCallBack {
        void callBack(List<Address> addresses);
    }

    // 获取地址信息
    private void getAddress(Location location, LocationCallBack callBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (location != null) {
                        Geocoder gc = new Geocoder(SelectAddressActivity.this, Locale.getDefault());
                        List<Address> result = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!isFinishing())
                                    callBack.callBack(result);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!isFinishing())
                                callBack.callBack(null);
                        }
                    });
                }
            }
        }).start();

    }

    private LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }

    };
}
